package org.repchain;

import com.rcjava.protos.Peer;
import com.rcjava.tran.TranCreator;
import com.rcjava.util.KeyUtil;
import org.bouncycastle.openssl.PEMParser;

import java.io.StringReader;
import java.security.PrivateKey;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 节点客户端 * * @author zyf
 */

public class ElectricBaseClient {

    public static final String ELECTRIC = "ElectricityTPL";
    public static final String CERT = "ContractCert";

    private String certFullName;
    private Peer.CertId certId;
    private Peer.ChaincodeId electricId;
    private TranCreator tranCreator;
    private static ConcurrentHashMap<String, ElectricBaseClient> userClientMap = new ConcurrentHashMap<>();

    public ElectricBaseClient(String creditCode, String certName,String privateKeyPem,String chianCodeName) {
        this.electricId = Peer.ChaincodeId.newBuilder().setChaincodeName(chianCodeName).setVersion(1).build();
        certFullName = creditCode + "." + certName;
        certId = Peer.CertId.newBuilder().setCreditCode(creditCode).setCertName(certName).build();
        PEMParser parser = new PEMParser(new StringReader(privateKeyPem));
        try {
            PrivateKey privateKey = KeyUtil.generatePrivateKey(parser, false, "");
            tranCreator = TranCreator.newBuilder().setPrivateKey(privateKey).setSignAlgorithm("sha1withecdsa").build();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public static ElectricBaseClient getClient(String creditCode, String certName,String privateKeyPem,String chianCodeName) {
        if (userClientMap.containsKey(creditCode+chianCodeName)) {
            return userClientMap.get(creditCode+chianCodeName);
        } else {
            ElectricBaseClient userClient = new ElectricBaseClient(creditCode, certName,privateKeyPem,chianCodeName);
            userClientMap.put(creditCode+chianCodeName, userClient);
            return userClientMap.get(creditCode+chianCodeName);
        }
    }

    public String getCertFullName() {
        return certFullName;
    }

    public void setCertFullName(String certFullName) {
        this.certFullName = certFullName;
    }

    public Peer.CertId getCertId() {
        return certId;
    }

    public void setCertId(Peer.CertId certId) {
        this.certId = certId;
    }

    public Peer.ChaincodeId getElectricId() {
        return electricId;
    }

    public void setElectricId(Peer.ChaincodeId electricId) {
        this.electricId = electricId;
    }

    public TranCreator getTranCreator() {
        return tranCreator;
    }

    public void setTranCreator(TranCreator tranCreator) {
        this.tranCreator = tranCreator;
    }
}

